import { Router } from 'vue-router';
import store from '/@/store';
import { parse, stringify } from 'qs';
import vueWechatAuth from '/@/plugins/vueWechatAuth';
import { getAccessToken } from '../api/api';
import { ResultData } from '../types';

const whitePathList: string[] = ['/intro', '/detail'];

export function createWechatGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (whitePathList.includes(to.path)) {
      next();
      return;
    }
    const {
      query: { code, testAuth },
    } = to;
    const { loginStatus, scopeNumber, accessToken } = store.getters;
    if (!accessToken) {
      // alert('no access token');
      switch (loginStatus) {
        case 0:
          if (testAuth) {
            await store.dispatch('getUserInfo', { code, testAuth });
            next();
            return;
          }
          const reurl = processUrl();

          vueWechatAuth.redirectUri = reurl;
          vueWechatAuth.setScope(scopeNumber);
          // alert(scopeNumber);

          // next();
          // break;
          await store.dispatch('setLoginStatus', 1);
          // alert(vueWechatAuth.authUrl);
          // next();
          window.location.href = vueWechatAuth.authUrl;
          break;
        // break;
        case 1:
          vueWechatAuth.returnFromWechat(to.fullPath);
          // alert('111111');
          if (!code && !scopeNumber) {
            store.dispatch('setLoginStatus', 0);
            location.reload();
            return;
          }
          if (code) {
            await store.dispatch('setLoginStatus', 2);
            await store.dispatch('getUserInfo', { code, testAuth });
          }
          next();
          break;
        case 2:
          next();
          break;
      }
    } else {
      // alert('you have access token');
    }
    next();
  });
}

async function getToken(testAuth: string) {
  // await store.dispatch("setCode", vueWechatAuth.code);
  await store.dispatch('setLoginStatus', 2);
  const { token, user } = (await getAccessToken(
    vueWechatAuth.code,
    Number(testAuth)
  )) as ResultData;
  store.dispatch('setAccessToken', token);
  store.dispatch('setUserInfo', user);
}

/**
 * 处理url链接
 */
function processUrl(): string {
  const url = window.location.href;
  // 解决多次登录url添加重复的code与state问题
  const [preurl, param] = url.split('?');
  const params = parse(param);
  let redirectUrl = url;
  if (params.code && params.state) {
    delete params.code;
    delete params.state;
    const query = stringify(params);
    if (query.length) {
      redirectUrl = `${preurl}?${query}`;
    } else {
      redirectUrl = preurl;
    }
  }
  return redirectUrl;
}
